package DataStructure.LinkedList;

import java.awt.*;

/**
 * @Author：DijaH
 * @Date：2023/2/5 12:59 下午
 * @Version：1.0.0
 * @Description： k个一组进行反转
 */
public class reverseKGroup {
    public ListNode reverseKGroup(ListNode head,int k){
        //base case
        if(head == null){
            return  head;
        }
        //区间[a,b)包含k个待反转的链表
        ListNode a,b;
        a = b = head;
        //a到b不满足k个的时候不用反转
        for(int i = 0; i < k; i++){
            if(b == null){
                return head;
            }
            b = b.next;
        }
        //反转链表
        ListNode reNode = reverse(a,b);
        //递归
        a.next = reverseKGroup(b,k);
        return reNode;
    }

    //反转区间[a,b)的链表
    public static ListNode reverse(ListNode a ,ListNode b){
        ListNode cur , pre , next;
        cur = next = a;
        pre = null;
        while(cur != b){
            next = cur.next;
            cur.next = pre;
            pre =cur;
            cur = next;
        }
        return pre;
    }
}
